<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Article;
use App\Http\Models\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    // GET|HEAD admin/article 全部列表
    public function index()
    {
        $data = Article::orderBy('art_order','asc')->paginate(5);;
        return view('admin.article.index',compact('data'));
    }

    // GET|HEAD admin/article/create 创建分类
    public function create()
    {
        return view('admin.article.add');
    }

    // POST admin/article 入库
    public function store()
    {
        $input = Input::except('_token');
        $input['art_time'] = time();
        // Validator 验证
        $rules = ['art_title'=>'required','art_content'=>'required'];
        $message = ['art_title.required'=>'文章标题不能为空!','art_content.required'=>'文章内容不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
           $res = Article::create($input);
           if($res){
               return redirect('admin/article');
           }else{
               return back()->with('errors','文章添加失败!');
           }
        }else{
           return back()->withErrors($validator);
        }
    }

    // 编辑 get admin/article/{id}/edit
    public function edit($art_id)
    {
        $field = Article::find($art_id);
        return view('admin.article.edit',compact('field'));
    }

    // PUT|PATCH admin/article/{id} 更新分类
    public function update($art_id)
    {
       $input = Input::except('_token','_method');
       $res = Article::where('art_id',$art_id)->update($input);
        if($res){
            return redirect('admin/article');
        }else{
            return back()->with('errors','文章更新失败!');
        }
    }

    // DELETE admin/article/{id} 删除单篇文章
    public function destroy($art_id)
    {
       $res = Article::where('art_id',$art_id)->delete();
        if($res){
            return array('status'=>0,'msg'=>'文章删除成功!');
        }else{
            return array('status'=>1,'msg'=>'文章删除失败!');
        }
    }

    // ajsx 修改排序
    public function changeOrder()
    {
        $input = Input::all();
        $field = Article::find($input['art_id']);
        $field->art_order = $input['art_order'];
        $res = $field->update();
        $data = array();
        if($res){
            $data['status'] = 0;
            $data['msg'] = '排序修改成功!';
        }else{
            $data['status'] = 1;
            $data['msg'] = '排序修改失败,请稍后再试!';

        }
        return $data;

    }

}
